<template>
  <div class="content-card">
    <div class="page-header">
      <h2>支付记录</h2>
      <el-button type="primary" @click="handleExport">导出记录</el-button>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-form :model="searchForm" class="search-form">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" />
      </el-form-item>
      <el-form-item label="支付流水号" prop="paymentNo">
        <el-input v-model="searchForm.paymentNo" placeholder="请输入支付流水号" />
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-select v-model="searchForm.paymentMethod" placeholder="请选择支付方式">
          <el-option label="全部" value="" />
          <el-option label="支付宝" value="1" />
          <el-option label="微信支付" value="2" />
          <el-option label="银行卡" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择支付状态">
          <el-option label="全部" value="" />
          <el-option label="支付成功" value="1" />
          <el-option label="支付失败" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付时间" prop="timeRange">
        <el-date-picker
          v-model="searchForm.timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 支付记录表格 -->
    <el-table 
      v-loading="loading" 
      :data="paymentList" 
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="paymentNo" label="支付流水号" min-width="200" />
      <el-table-column prop="orderNo" label="订单编号" min-width="180" />
      <el-table-column prop="userId" label="用户ID" width="100" />
      <el-table-column prop="amount" label="支付金额" width="100" formatter="formatPrice" />
      <el-table-column prop="paymentMethod" label="支付方式" width="120">
        <template #default="scope">
          {{ getPaymentMethodText(scope.row.paymentMethod) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="支付状态" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '支付成功' : '支付失败' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="paymentTime" label="支付时间" width="180" />
      <el-table-column prop="channelTradeNo" label="渠道交易号" min-width="200" />
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination">
      <div class="pagination-info">
        共 {{ total }} 条记录，每页显示 {{ pageSize }} 条
      </div>
      <el-pagination 
        v-model:current-page="currentPage" 
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedPayments.length > 0">
      <el-button type="primary" @click="handleBatchExport">批量导出</el-button>
    </div>
  </div>
</template>

<script>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { paymentApi } from '../../api/payment.js'

export default {
  name: 'PaymentList',
  setup() {
    const loading = ref(false)
    const paymentList = ref([])
    const selectedPayments = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // 搜索表单
    const searchForm = reactive({
      orderNo: '',
      paymentNo: '',
      paymentMethod: '',
      status: '',
      timeRange: []
    })
    
    // 格式化价格
    const formatPrice = (row, column, cellValue) => {
      return `¥${cellValue.toFixed(2)}`
    }
    
    // 获取支付方式文本
    const getPaymentMethodText = (method) => {
      const methodMap = {
        1: '支付宝',
        2: '微信支付',
        3: '银行卡'
      }
      return methodMap[method] || '未知'
    }
    
    // 获取支付记录列表
    const getPaymentList = async () => {
      loading.value = true
      try {
        const params = {
          ...searchForm,
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }
        
        // 模拟API请求，使用mock数据
        setTimeout(() => {
          paymentList.value = generateMockData()
          total.value = 100
          loading.value = false
        }, 500)
        
        // 实际API调用代码（目前注释掉）
        // const response = await paymentApi.getPaymentList(params)
        // paymentList.value = response.data.list
        // total.value = response.data.total
        // loading.value = false
      } catch (error) {
        console.error('获取支付记录列表失败:', error)
        ElMessage.error('获取支付记录列表失败')
        loading.value = false
      }
    }
    
    // 生成模拟数据
    const generateMockData = () => {
      const payments = []
      
      for (let i = 0; i < pageSize.value; i++) {
        const index = (currentPage.value - 1) * pageSize.value + i + 1
        const paymentMethod = Math.floor(Math.random() * 3) + 1
        const status = Math.random() > 0.1 ? 1 : 0 // 90%概率支付成功
        
        payments.push({
          id: index,
          paymentNo: `PAY-${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(new Date().getDate()).padStart(2, '0')}-${String(index).padStart(6, '0')}`,
          orderNo: `ORD-${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(new Date().getDate()).padStart(2, '0')}-${String(index).padStart(4, '0')}`,
          userId: Math.floor(Math.random() * 10000) + 1,
          amount: Math.floor(Math.random() * 5000) + 100,
          paymentMethod: paymentMethod,
          status: status,
          paymentTime: new Date(Date.now() - Math.floor(Math.random() * 30 * 24 * 60 * 60 * 1000)).toLocaleString(),
          channelTradeNo: status === 1 ? `${paymentMethod === 1 ? 'ALIPAY' : paymentMethod === 2 ? 'WECHAT' : 'BANK'}-${Math.floor(Math.random() * 10000000000)}` : ''
        })
      }
      
      return payments
    }
    
    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      getPaymentList()
    }
    
    // 处理重置
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        if (key === 'timeRange') {
          searchForm[key] = []
        } else {
          searchForm[key] = ''
        }
      })
      currentPage.value = 1
      getPaymentList()
    }
    
    // 处理分页大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
      getPaymentList()
    }
    
    // 处理当前页码变化
    const handleCurrentChange = (current) => {
      currentPage.value = current
      getPaymentList()
    }
    
    // 处理选择变化
    const handleSelectionChange = (selection) => {
      selectedPayments.value = selection
    }
    
    // 处理查看详情
    const handleDetail = (payment) => {
      // 这里可以打开支付详情弹窗或者跳转到详情页面
      ElMessage.info('查看支付详情：' + payment.paymentNo)
    }
    
    // 处理导出记录
    const handleExport = async () => {
      try {
        // 模拟导出请求
        setTimeout(() => {
          ElMessage.success('支付记录导出成功')
        }, 1000)
        
        // 实际API调用代码（目前注释掉）
        // await paymentApi.exportPaymentData(searchForm)
        // ElMessage.success('支付记录导出成功')
      } catch (error) {
        console.error('导出支付记录失败:', error)
        ElMessage.error('导出支付记录失败')
      }
    }
    
    // 处理批量导出
    const handleBatchExport = async () => {
      try {
        const ids = selectedPayments.value.map(payment => payment.id)
        // 模拟批量导出请求
        setTimeout(() => {
          ElMessage.success('批量导出成功')
          selectedPayments.value = []
        }, 1000)
        
        // 实际API调用代码（目前注释掉）
        // await paymentApi.batchExportPayments(ids)
        // ElMessage.success('批量导出成功')
        // selectedPayments.value = []
      } catch (error) {
        console.error('批量导出失败:', error)
        ElMessage.error('批量导出失败')
      }
    }
    
    // 初始化数据
    onMounted(() => {
      getPaymentList()
    })
    
    return {
      loading,
      paymentList,
      selectedPayments,
      total,
      currentPage,
      pageSize,
      searchForm,
      formatPrice,
      getPaymentMethodText,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      handleDetail,
      handleExport,
      handleBatchExport
    }
  }
}
</script>

<style scoped lang="scss">
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  
  .el-form-item {
    margin-right: 20px;
    margin-bottom: 15px;
  }
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  
  .pagination-info {
    color: var(--text-secondary);
    font-size: 14px;
  }
}

.batch-actions {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
  
  .el-button {
    margin-right: 10px;
  }
}
</style>